<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test.js"></script>
<script src="resources/common.js"></script>
</head>
<body>
<p id="description"></p>
<div id="console"></div>

<script>
description("Tests importing an AES key from raw with wrong length");

jsTestIsAsync = true;

// -------------------------------------------------
// Failed key import.
// -------------------------------------------------

// Supported key lengths are 16 (128-bit), 32 (256-bit), 24 (192-bit),
// Try key lengths that are off by 1 from the supported ones.
var kUnsupportedKeyLengths = [
    0, 1, 15, 17, 31, 33, 23, 25, 64
];

// Not exhaustive
var kAesAlgorithms = [
  "AES-CBC", "AES-GCM", "AES-KW"
];

function testInvalidKeyImport(algorithmName, keyLengthBytes)
{
    var algorithm = {name: algorithmName};
    var keyData = new Uint8Array(keyLengthBytes);

    var usages = ['encrypt', 'decrypt'];
    var extractable = false;

    return crypto.subtle.importKey('raw', keyData, algorithm, extractable, usages).then(function(result) {
        debug("FAIL: Successfully imported " + algorithmName + " key of length " + keyData.byteLength + " bytes");
    }, function(result) {
        debug("PASS: Failed to import " + algorithmName + " key of length " + keyData.byteLength + " bytes");
    });
}

var lastPromise = Promise.resolve(null);

kAesAlgorithms.forEach(function(algorithmName) {
    kUnsupportedKeyLengths.forEach(function(keyLengthBytes) {
        lastPromise = lastPromise.then(testInvalidKeyImport.bind(null, algorithmName, keyLengthBytes));
    });
});

lastPromise.then(finishJSTest, failAndFinishJSTest);

</script>

</body>
</html>
